package com.keepers.repair.net;

import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.keepers.repair.model.GetTaskListByIDModel;
import com.keepers.repair.model.LineAndPlaceListModel;
import com.keepers.repair.model.LoginModel;
import com.keepers.repair.model.NotificationsModel;
import com.keepers.repair.model.RepairListModel;
import com.keepers.repair.model.TaskMaintenanceListModel;
import com.keepers.repair.model.UserListModel;
import com.keepers.repair.utils.Config;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.HttpUrl;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * auth aboom
 * date 2018/10/21
 */
public class DataLoader {

    private static String socketUrl = new HttpUrl.Builder()
            .scheme("http")
            .host(Config.socketHost)
            .port(Config.socketPort)
            .build()
            .toString() + "/";

    /**
     * 登录
     */
    public static Disposable login(String userName, String password, Call<LoginModel> call) {
        return getApi().login(userName, password)
                .compose(RxTransformerHelper.applySchedulersResult())
                .subscribe(s -> {
                    call.call(JSONObject.parseObject(s, LoginModel.class));
                }, call(call));
    }

    public static Disposable logout(String userId, Call<Boolean> call) {
        return getApi().logout(userId)
                .compose(RxTransformerHelper.applySchedulersResult())
                .subscribe(s -> call.call("true".equals(s)), call(call));
    }

    /**
     * 修改密码
     */
    public static Disposable setPassword(String userGid, String password, Call<Boolean> call) {
        return getApi().setPassword(userGid, password)
                .compose(RxTransformerHelper.applySchedulersResult())
                .subscribe(s -> call.call("true".equals(s)), call(call));
    }


    public static Disposable getNotification(String groupGid, String userGid, Call<NotificationsModel> call) {
        return getApi().getNoticeList(groupGid, userGid)
                .compose(RxTransformerHelper.applySchedulersResult())
                .subscribe(s -> call.call(JSONObject.parseObject(s, NotificationsModel.class)), call(call));
    }


    public static Disposable getTaskList(String groupGid, String userGid, int type, Call<GetTaskListByIDModel> call) {
        return getApi().getTaskList(groupGid, userGid, type)
                .compose(RxTransformerHelper.applySchedulersResult())
                .subscribe(s -> call.call(JSONObject.parseObject(s, GetTaskListByIDModel.class)), call(call));
    }


    public static Disposable getLineAngdPlaceInforByID(String taskId, Call<LineAndPlaceListModel> call) {
        return getApi().getLineAngdPlaceInforByID(taskId)
                .compose(RxTransformerHelper.applySchedulersResult())
                .subscribe(s -> call.call(JSONObject.parseObject(s, LineAndPlaceListModel.class)), call(call));
    }

    public static Disposable submitRepairTask(String userGid, Call<Boolean> call) {
        return getApi().submitRepairTask(userGid)
                .compose(RxTransformerHelper.applySchedulersResult())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                    }
                }, call(call));

    }

    public static Disposable uploadOverhaulResult(String rGid, String record, Call<Boolean> call) {
        return getApi().uploadOverhaulResult(rGid, record)
                .compose(RxTransformerHelper.applySchedulersResult())
                .subscribe(s -> call.call("true".equals(s)), call(call));
    }

    public static Disposable repairUploadFiles(String fileName, int type, String rGid, String fileStr, Call<Boolean> call) {
        return getApi().repairUploadFiles(fileName, type, rGid, fileStr)
                .compose(RxTransformerHelper.applySchedulersResult())
                .subscribe(s -> call.call("true".equals(s)), call(call));
    }

    public static Disposable getRepairTaskList(String userGid, String groupGid, Call<TaskMaintenanceListModel> call) {
        return getApi().GetRepairTaskList(groupGid, userGid)
                .compose(RxTransformerHelper.applySchedulersResult())
                .subscribe(s -> call.call(JSONObject.parseObject(s, TaskMaintenanceListModel.class)), call(call));
    }

    public static Disposable getRepairList(String userId, String groupGid, Call<RepairListModel> call) {
        return getApi().getRepairList(userId, groupGid)
                .compose(RxTransformerHelper.applySchedulersResult())
                .subscribe(s -> call.call(JSONObject.parseObject(s, RepairListModel.class)), call(call));
    }


    public static Disposable makeRepair(String userId, String groupGid, String gpsId, String repairUserId, String repairInfo, Call<Boolean> call) {
        Log.e("aa", " userId = " + userId + " groupGid = " + groupGid + " gpsId = " + gpsId + " repairUserId = " + repairUserId + " repairInfo = " + repairInfo);
        return getApi().makeRepair(userId, groupGid, gpsId, repairUserId, repairInfo)
                .compose(RxTransformerHelper.applySchedulersResult())
                .subscribe(s -> call.call("true".equals(s)), call(call));
    }

    public static Disposable getOverhaulList(String userId, String groupGid, int type, Call<UserListModel> call) {
        return getApi().getOverhaulList(userId, groupGid, type)
                .compose(RxTransformerHelper.applySchedulersResult())
                .subscribe(s -> call.call(JSONObject.parseObject(s, UserListModel.class)), call(call));
    }

    public static Disposable saveSOSInfor(String base64Str,
                                          String saveName,
                                          String userGid,
                                          String treeGid,
                                          String taskGid,
                                          String taskPGid,
                                          String placeGid,
                                          String devicePhone,
                                          String longitude,
                                          String latitude,
                                          String dataTime,
                                          Call<Boolean> call) {
        return getApi().SaveSOSInfor(base64Str, saveName, userGid, treeGid, taskGid, taskPGid, placeGid, devicePhone, longitude, latitude, dataTime)
                .compose(RxTransformerHelper.applySchedulersResult())
                .subscribe(s -> call.call("true".equals(s)), call(call));
    }

    /**
     * 上传聊天语音
     *
     * @param fileInfo 语音文件流信息
     * @param fileName 文件保存名
     * @param userId   用户 ID
     * @param groupGid 用户组 ID
     * @param length   语音的时长
     */
    public static Disposable uploadChatVoice(String userId, String groupGid, String fileInfo, String fileName, int length, Call<String> call) {
        return getApi().saveChatVoice(fileInfo, fileName, userId, groupGid, length)
                .compose(RxTransformerHelper.applySchedulersResult())
                .subscribe(call::call, call(call));
    }

    /**
     * 下载语音文件
     *
     * @param name 文件名
     */
    public static Disposable downloadChatVoice(String name, Call<ResponseBody> call) {
        String url = Config.voiceUrl + name;
        return getApi().downloadChatVoice(url)
                .compose(RxTransformerHelper.applySchedulersAndAllFilter())
                .map(result -> {
                    Response<ResponseBody> response = result.response();
                    if (response != null) {
                        ResponseBody body = response.body();
                        if (body != null) {
                            return body;
                        }
                    }
                    throw new Exception("data is null");
                })
                .subscribe(call::call, call(call));
    }


    public static String getSocketUrl() {
        return socketUrl;
    }



    private static Consumer<Throwable> call(Call<?> call) {
        return throwable -> {
            LogUtil.e("aa", throwable.getMessage());
            call.call(null);
        };
    }


    private static LoaderService getApi() {
        return DataServiceProvider.getInstance().provide(LoaderService.class);
    }
}
